<?php
namespace Modules\Home\Controllers;

use \Common\Models\UserModel;

class UserController extends ControllerBase {
  public function initialize() {
    parent::initialize();

    $this -> _checkLogin();
    $this -> view -> setLayout('index');
  }

  public function indexAction() {
    $this -> tag -> prependTitle('用户');
  }

  public function useUserCodeGetUserNameAction() {
    $userCode = $this -> request -> get('user_code', 'int', null, true);
    
    $this -> response -> setContentType('application/json', 'UTF-8');
    if(!$userCode) {
      return $this -> response -> setJsonContent(['code' => -1, 'message' => '推荐人编号为空']);
    }

    $findFirstUser = UserModel::findFirst('user_code = "' . $userCode . '"');

    if(!$findFirstUser) {
      return $this -> response -> setJsonContent(['code' => -1, 'message' => '推荐人不存在']);
    }

    return $this -> response -> setJsonContent(['code' => 0, 'data' => ['real_name' => $findFirstUser -> real_name]]);
  }

  public function useUserCodeGetUserNameAndNodeAction() {
    $userCode = $this -> request -> get('user_code', 'int', null, true);
    
    $this -> response -> setContentType('application/json', 'UTF-8');
    if(!$userCode) {
      return $this -> response -> setJsonContent(['code' => -1, 'message' => '接点人编号为空']);
    }

    $findFirstUser = UserModel::findFirst('user_code = "' . $userCode . '"');

    if(!$findFirstUser) {
      return $this -> response -> setJsonContent(['code' => -1, 'message' => '接点人不存在']);
    }

    $findUserNoedSide = UserModel::find('node_user_id = ' . $findFirstUser -> user_id . ' AND node_side in(1, 2)');
    if($findUserNoedSide -> count() >= 2) {
      return $this -> response -> setJsonContent(['code' => -1, 'message' => '左右区已满']);
    }

    $nodeSide = [
      1 => '左区',
      2 => '右区',
    ];
    foreach($findUserNoedSide as $userNoedSide) {
      unset($nodeSide[$userNoedSide -> node_side]);
    }

    return $this -> response -> setJsonContent(['code' => 0, 'data' => ['real_name' => $findFirstUser -> real_name, 'node_side' => $nodeSide]]);
  }
}
?>